from flask import session
import functools
import random
import hashlib

''' 登录装饰器 '''
def login_required(func):
    @functools.wraps(func)
    def user_login(*args, **kw):
        if "user_id" in session:
            user_id = session['user_id']
            if user_id is not None:
                return func(*args, **kw)
        return False
    return user_login
        
''' 随机生成指定长度字符串 '''
def create_nonce_str(length = 6):
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return "".join(random.sample(chars, length))

''' md5加密 '''
def md5(str):
    md5 = hashlib.md5()
    md5.update(str.encode('utf-8'))
    return md5.hexdigest()

''' 创建用户密码 '''
def create_password(password, salt):
    return md5(md5(password) + salt)

''' 生成树 '''
def generate_tree(data, parent_id = 0, is_dict = False):
    tree = []
    if is_dict == True:
        for item in data:
            if item['parent_id'] == parent_id:
                item['children'] = generate_tree(data, item['id'], is_dict)
                tree.append(item)
    else:
        for item in data:
            if item.parent_id == parent_id:
                item.children = generate_tree(data, item.id, is_dict)
                tree.append(item)
    return tree

def get_children(data, return_data = []):
    for item in data:
        return_data.append(item)
        if getattr(item, 'children', None):
            get_children(item.children, return_data)
    return return_data

''' 无限分类 '''
def generate_tree2(return_data, data, parent_id = 0, level = 0):
    for item in data:
        if item.parent_id == parent_id:
            item.level = level
            return_data.append(item)
            generate_tree2(return_data, data, item.id, level + 1)
    return return_data